<template>
  <div class='login'>
    <!-- 导航栏 -->
    <van-nav-bar
      title="登录"
    />
    <!-- 表单部分
    :rules="[{ required: true, message: '请填写用户名' }]"
    van-field的error-message属性 错误提示
    :error-message="errInfo.mobile"
     -->
    <van-form @submit="onSubmit">
      <van-field
        v-model.trim="userInfo.mobile"
        required
        name="手机号"
        label="手机号"
        placeholder="请填写手机号"
        :rules="[{ pattern: /^1[3456789]\d{9}$/, message: '请输入正确手机号', trigger: 'onBlur'}]"
      />
      <van-field
        v-model.trim="userInfo.code"
        required
        type="password"
        name="密码"
        label="密码"
        placeholder="请填写密码"
        :rules="[{ pattern: /^\d{6}$/, message: '请输入正确密码', trigger: 'onBlur' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from '@/api/user.js';
import { mapMutations } from 'vuex';
export default {
  name: 'LoginIndex',
  props: { },
  data () {
    return {
      userInfo: {
        mobile: '13912345678',
        code: '246810'
      }
      // 保存错误信息
      // errInfo: {
      //   mobile: '',
      //   code: ''
      // },
    };
  },
  computed: { },
  created () { },
  mounted () { },
  methods: {
    ...mapMutations(['mSetToken']),
    async onSubmit () {
      // ajax请求之前添加loading
      this.$toast.loading({
        message: '登录中...',
        mask: false, // 整体添加一个遮罩层
        duration: 0 // 0表示这个提示不会消失，可以用一个新的toast来覆盖它
      });
      const { mobile, code } = this.userInfo;
      try {
        const result = await userLogin(mobile, code);
        console.log(result);
        // ajax请求之后取消loading,用一个新的toast来覆盖它
        this.$toast.success('登录成功');
        // 把token保存在vuex中
        // 调用mutation保存token信息到vuex中
        // 方法一：直接设置
        // this.$store.commit('mSetToken', result.data.data);
        // 方法二：通过mapMutations设置,记得导入vuex
        this.mSetToken(result.data.data);

        // 跳转到主页
        // this.$router.push('/');
        // 之前要去哪里就跳到哪里
        const jumpto = this.$route.query.backto || '/';
        this.$router.push(jumpto);
      } catch (error) {
        console.log(error.message);
        // 登录失败
        this.$toast.fail('登录失败');
      }
    }
  }
};
</script>

<style scoped lang='less'>
</style>
